<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Numbers in Ruby: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="numbers in ruby,ruby study notes,free ruby programming guide,ruby guide,free ruby programming course,best ruby guide,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/numbers_in_ruby.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>

<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Ruby Learning site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Numbers in Ruby</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/features.html">&lt;Features | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/fun_with_strings.html">Fun with Strings&gt;</a>
                  </strong>
                </p>

                <p>Let's play with Numbers. In Ruby, numbers without decimal points are called integers, and numbers with decimal points are usually called floating-point numbers or, more simply, floats (you must place at least one digit before the decimal point). An integer literal is simply a sequence of digits eg. 0, 123, 123456789. Underscores may be inserted into integer literals (though not at the beginning or end), and this feature is sometimes used as a thousands separator eg. 1_000_000_000. Underscore characters are ignored in the digit string. Here's program <strong>p002rubynumbers.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p002rubynumbers.rb
                =begin
                 Ruby Numbers
                 Usual operators:
                 + addition
                 - subtraction
                 * multiplication
                 / division
                =end

                puts 1 + 2
                puts 2 * 3
                # Integer division
                # When you do arithmetic with integers, you'll get integer answers
                puts 3 / 2
                puts 10 - 11
                puts 1.5 / 2.6
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p class="post-note">Ruby integers are objects of class <strong>Fixnum</strong> or <strong>Bignum</strong>. The <strong>Fixnum</strong> and <strong>Bignum</strong> classes represent integers of differing sizes. Both classes descend from <strong>Integer</strong> (and therefore <strong>Numeric</strong>). The floating-point numbers are objects of class <strong>Float</strong>, corresponding to the native architecture's double data type. The <strong>Complex</strong>, <strong>BigDecimal</strong>, and <strong>Rational</strong> classes are not built-in to Ruby but are distributed with Ruby as part of the standard library. We shall be talking about <a href="/satishtalim/writing_our_own_class_in_ruby.html">classes</a> in detail later.</p>

                <p>A part of the class hierarchy is as shown in the figure below:</p>

                <p><a href="/images/class.png" title="Class Hierarchy"><img src="/images/class.png" width="600" alt="Class Hierarchy" /></a></p>

                <h3>Operators and Precedence</h3>

                <p>Let us look at Ruby's operators (courtesy: Dave Thomas' - <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0" >Programming Ruby</a>). They are arranged here in order from highest to lowest precedence.</p>

                <p><a href="/images/operators.jpg" title="Operators in Ruby"><img src="/images/operators.jpg" alt="Operators in Ruby" /></a></p>

                <p class="post-note">a. The increment and decrement operators (++ and --) are not available in Ruby, neither in "pre" nor "post" forms. However, do note that the += and -= are available.<br />b. Brackets (parentheses) work the same way as with regular arithmetic. Anything inside brackets is calculated first (or, more technically, given higher precedence).<br />c. The check marked operators is a kind of syntactic sugar (more on this later) - where something looks like an operator but is a method call.</p>

                <p>The Ruby modulus operator's (%) behavior is as follows:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                puts (5 % 3)     # prints  2
                puts (-5 % 3)    # prints  1
                puts (5 % -3)    # prints -1
                puts (-5 % -3)   # prints -2
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Ruby's definition of the <a href="http://en.wikipedia.org/wiki/Modulo_operation">modulo</a> (%) operator differs from that of C and Java. In Ruby, -7%3 is 2. In C and Java, the result is -1 instead. In Ruby, <strong>the sign of the result (for % operator) is always the same as the sign of the second operand.</strong></p>

                <h3>Difference between or and || operator.</h3>

                <p>Both <strong>or</strong> and <strong>||</strong> return their first argument unless it is <strong>false</strong>, in which case they evaluate and return their second argument. This is shown in the following example:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                puts nil || 2008
                puts false || 2008
                puts "ruby" || 2008
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby test.rb
                2008
                2008
                ruby
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The only difference between <strong>or</strong> and <strong>||</strong> is their precedence. <strong>||</strong> has a higher precedence than <strong>or</strong>.<br /><br />A common idiom is to use <strong>||</strong> to assign a value to a variable only if that variable isn't already set. This can be written as:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                @variable = @variable || "default value"
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>or, more idiomatically, as:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                @variable ||= "default value"
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>One reason for these alternate versions of the Boolean operators is the fact that they have lower precedence than the assignment operator. This means that you can write a Boolean expression such as the following that assigns values to variables until it encounters a false value:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                if a = f(x) and b = f(y) and c = f(z) then d = g(a,b,c) end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>This expression simply would not work as intended, if written with <strong>&amp;&amp;</strong> instead of <strong>and</strong>.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                def g *args # The splat here says accept 1 or more arguments, in the form of an Array
                  args      # This returns an array
                end

                def f arg
                  arg
                end

                x,y,z = [true, 'two', false] # parrallel assignment lets us do this

                if a = f(x) and b = f(y) and c = f(z) then
                  d = g(a,b,c) # An array is returned, and stored in variable d
                end

                p d # using p to puts and inspect d
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/features.html">&lt;Features | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/fun_with_strings.html">Fun with Strings&gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">

            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->

</body>
</html>
